<?php
include("database.class.php");

$db = new Database("../mysqlconfig.txt");
$link = $db->connectWithDb();

if($_SERVER['REQUEST_METHOD'] != "POST") {
?>
<h1>Enter your username and email to get a new password</h1>
<form method="POST">
	<table>
	<tr><td>Name:</td><td><input type="text" name="name"></td></tr>
	<tr><td>Email:</td><td><input type="text" name="email"></td></tr>
	<tr><td colspan="2"><input type="submit" name="submit" value="Send me a new password."></td></tr>
	</table>
</form>
<?php
}
else { // posted
	$email = $_POST['email'];
	$name = $_POST['name'];
	
	if(!preg_match("/^([-0-9a-zA-Z_]){4,15}$/", $name)) {
		die("ERROR: Please give a name that will pass '^([-0-9a-Z_]){4,15}$'.");
	}
	
	if(!preg_match('/^[A-Za-z0-9\+._-]+@[A-Za-z0-9._-]+\.[A-Za-z]{2,6}$/', $email)) {
		die("ERROR: Please give a valid email address.");
	}
	
	$ret = $db->executeQuery($link, "SELECT COUNT(*) AS rows FROM users WHERE email='$email' AND name='$name'");
	
	if($ret['rows'] == 1) {
		$arr = array_merge(range("a", "z"), range("A", "Z"), range("0", "9"));
		$pass = "";
		for($i=0; $i<8; $i++) {
			$pass .= $arr[rand(0,count($arr)-1)];
		}
		mail($email, "New password for ThinkChat", "Your new password is $pass");
		$pass = md5($pass);
		$db->executeQuery($link, "UPDATE users SET pass='$pass' WHERE email='$email' AND name='$name'");
		
		echo "Your password is changed, check your mailbox (and spam folder)";
	}
	else {
		echo "Something went wrong! Please supply valid data.";
	}
}
?>
